package org.trimard;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class Main extends Activity
{
	private static final String TAG=Main.class.getName();

	private SailChartView sailChartView;

	private SharedPreferences sharedPrefs;

	@Override
    public void onCreate(Bundle savedInstanceState)
	{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sailChartView=new SailChartView(this, getLinearLayout(R.id.chartLayout));

        sharedPrefs=PreferenceManager.getDefaultSharedPreferences(this);

		// Create the adView
	    AdView adView = new AdView(this, AdSize.BANNER, "a14dda800f764f8");
	    getLinearLayout(R.id.adLayout).addView(adView);
	    // Initiate a generic request to load it with an ad
	    AdRequest adRequest=new AdRequest();
		adView.loadAd(adRequest);

		if(sharedPrefs.getBoolean(PreferenceConstant.SHOW_HELP_KEY, true))
			showHelp();
    }

	protected LinearLayout getLinearLayout(int id)
	{
		return (LinearLayout)findViewById(id);
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		sailChartView.destroy();
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	getMenuInflater().inflate(R.menu.menu, menu);
    	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	if(item.getItemId()==R.id.preferencesMenuItem)
    	{
    		Intent intent=new Intent(this, Preferences.class);
    		startActivity(intent);
    	}
    	else if(item.getItemId()==R.id.aboutMenuItem)
    	{
    		try
			{
				AboutDialogBuilder.create(this, getString(R.string.about)).show();
			}
			catch (NameNotFoundException e)
			{
				Log.e(TAG, "Failed to display about dialog", e);
			}
    	}
    	else if(item.getItemId()==R.id.helpMenuItem)
    	{
    		showHelp();
    	}
    	return true;
    }

	protected void showHelp()
	{
		WebView wv = new WebView(this);
		String str = " Your own html code here! ";
		wv.loadData(str, "text/html", "utf-8");
		Dialog dialog = new Dialog(this) {
			@Override
			public boolean onKeyDown(int keyCode, KeyEvent event){
				if (keyCode != KeyEvent.KEYCODE_DPAD_LEFT)
					this.dismiss();
				return true;
			}
		};
		dialog.addContentView(wv, new LinearLayout.LayoutParams(100, 100));
		dialog.show();

		// Change preference
		Editor edit=sharedPrefs.edit();
		edit.putBoolean(PreferenceConstant.SHOW_HELP_KEY, false);
		edit.commit();
	}
}